//
//  GZ_RadioViewController.m
//  B段项目
//
//  Created by 高哲 on 15/11/3.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "GZ_RadioViewController.h"
#import "GZ_ScrollModel.h"
#import "GZRadioTableViewCell.h"
#import "GZ_HeaderImageVC.h"
#import "GZ_RadioDetailsVC.h"
@interface GZ_RadioViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)NSMutableArray *scrollArray;
@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, strong)GZ_ScrollModel *scrollModel;
@property(nonatomic, strong)UIPageControl *pageControl;
@property(nonatomic, strong)myView *bgView;
@property(nonatomic, strong)GZ_RadioModel *radioModel;

@property(nonatomic, strong)NSMutableArray *hArray;
@property(nonatomic, strong)NSMutableArray *allArray;

@property(nonatomic, strong)XMN_ProgressHUD *HUD;

@property(nonatomic,strong)NSString *urlString;
@property(nonatomic, strong)NSString *bodyString;
@property(nonatomic, assign)NSInteger start;

@property(nonatomic, strong)NSTimer *timer;
@end

@implementation GZ_RadioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
       self.title = @"电台";
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
    }



- (void)loadView
{
    [super loadView];
   
    _urlString = @"http://api2.pianke.me/ting/radio";
    _bodyString = @"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&version=3.0.6";
   
    _allArray = [NSMutableArray array];
    _scrollArray = [NSMutableArray array];
    _dataSourceArray = [NSMutableArray array];
    _hArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView NightWithType:UIViewColorType2];
    [self.view addSubview:_tableView];
    
    

//    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        _start = 0;
//        [self getData];
//    }];
//    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _start += 9;
//        [self getData];
//    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    _tableView.header = header;
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 1; i <= 9; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lda", i]];
        [array addObject:image];
    }
    [header setImages:array duration:1 forState:MJRefreshStatePulling];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    _tableView.footer = footer;
    [footer setImages:array duration:1 forState:MJRefreshStateRefreshing];
    [_tableView.header beginRefreshing];
    

    
    
}

- (void)getData
{
    if ([_tableView.header isRefreshing]) {
        _start =0 ;
    }
    else
    {
        _start += 9;
    }
   
    if (_start == 0) {
        _urlString = @"http://api2.pianke.me/ting/radio";
        _bodyString = @"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&version=3.0.6";
    }else{
        _urlString = @"http://api2.pianke.me/ting/radio_list";
        _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&limit=9&start=%ld&version=3.0.6", _start];
    }
    
    
    
[HTTPMethod getDataByString:_urlString BODYDic:[ChangeString changeStringToDictionary:_bodyString] WithDataBlock:^(id data) {
   
    NSDictionary *dataDic = [data valueForKey:@"data"];
    
    NSArray *scrollTempArray = [dataDic valueForKey:@"carousel"];
    if (!_start) {
        
        [_allArray removeAllObjects];
        [_scrollArray removeAllObjects];
        [_dataSourceArray removeAllObjects];
        [_hArray removeAllObjects];
        
        for (NSDictionary *scrollDic in scrollTempArray) {
            _scrollModel = [[GZ_ScrollModel alloc] init];
            [_scrollModel setValuesForKeysWithDictionary:scrollDic];
            [_scrollArray addObject:_scrollModel];
        }
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200 * FitHeight)];
        _scrollView.contentSize = CGSizeMake(ScreenWidth * (_scrollArray.count + 2), 200 * FitHeight);
        _scrollView.contentOffset = CGPointMake(ScreenWidth, 0);
        [_scrollView setPagingEnabled:YES];
        
        //隐藏横向滚动条
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        
        //头视图的父视图
        _bgView = [[myView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, _scrollView.frame.size.height + 150 * FitHeight)];
        
        [_bgView addSubview:_scrollView];
        //滚动视图添加图片
        for (NSInteger i = 1; i <= _scrollArray.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth * i, 0, ScreenWidth, _scrollView.frame.size.height)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:[_scrollArray[i - 1] img]] placeholderImage:[UIImage imageNamed:@"GZ_scroll.png"]];
            
            [_scrollView addSubview:imageView];
        }
        //循环设置图片
        UIImageView *imageViewFirst = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, _scrollView.frame.size.height)];
        [imageViewFirst sd_setImageWithURL:[NSURL URLWithString:[[_scrollArray lastObject] img]] placeholderImage:[UIImage imageNamed:@"GZ_scroll.png"]];
        [_scrollView addSubview:imageViewFirst];
        
        UIImageView *imageViewLast = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth * (_scrollArray.count + 1), 0, ScreenWidth, _scrollView.frame.size.height)];
        [imageViewLast sd_setImageWithURL:[NSURL URLWithString:[[_scrollArray firstObject] img]]placeholderImage:[UIImage imageNamed:@"GZ_scroll.png"]];
        [_scrollView addSubview:imageViewLast];
        //给滚动视图添加计时器
     _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
        
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(280 * FitWidth, 170 *FitHeight, 95 * FitWidth, 30 * FitHeight)];
        _pageControl.numberOfPages = _scrollArray.count;
        //选中点的颜色
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        [_pageControl addTarget:self action:@selector(pageControlAction) forControlEvents:UIControlEventValueChanged];
        [_bgView addSubview:_pageControl];
        
        NSArray *hotlistArray = [dataDic valueForKey:@"hotlist"];
        
        
        for (NSDictionary *Hdic in hotlistArray) {
            _radioModel = [[GZ_RadioModel alloc] init];
            [_radioModel setValuesForKeysWithDictionary:Hdic];
            [_hArray addObject:_radioModel];
        }
        
        //头视图三张图
        for (NSInteger i = 0; i < 3; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10 * FitWidth + i * 120 * FitWidth, _scrollView.frame.size.height + _scrollView.frame.origin.y + 7 * FitHeight, 115 * FitWidth, 115 * FitHeight)];
            [imageView setTag:1000 + i];
            UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerThreeImageTapAction:)];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:headerTap];
            [imageView sd_setImageWithURL:[NSURL URLWithString:[_hArray[i] coverimg]]];
            imageView.layer.cornerRadius = 8.0;
            imageView.layer.masksToBounds = YES;
            
            [_bgView addSubview:imageView];
        }
        UILabel *headerLable = [[UILabel alloc] initWithFrame:CGRectMake(10 * FitWidth, _scrollView.frame.size.height + _scrollView.frame.origin.y + 122 * FitHeight, 140 * FitWidth, 28 * FitHeight)];
        headerLable.text = @"全部电台·All Radios";
        headerLable.textColor = [UIColor lightGrayColor];
        [headerLable setFont:[UIFont systemFontOfSize:14]];
        [_bgView addSubview:headerLable];
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(headerLable.frame.size.width + headerLable.frame.origin.x, headerLable.frame.origin.y + 15, ScreenWidth - headerLable.frame.origin.x - headerLable.frame.size.width, 1)];
        headerView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
        [_bgView addSubview:headerView];
        _tableView.tableHeaderView = _bgView;
        
        NSArray *allTempArray = [dataDic valueForKey:@"alllist"];
        
        for (NSDictionary *allDic in allTempArray) {
            _radioModel = [[GZ_RadioModel alloc] init];
            [_radioModel setValuesForKeysWithDictionary:allDic];
            [_allArray addObject:_radioModel];
        }
        
    }
    else{
        NSArray *allTempArray = [dataDic valueForKey:@"list"];

        
        for (NSDictionary *allDic in allTempArray) {
            _radioModel = [[GZ_RadioModel alloc] init];
            [_radioModel setValuesForKeysWithDictionary:allDic];
            [_allArray addObject:_radioModel];
        }
    }
    
    [_tableView reloadData];
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    
     [_HUD removeFromSuperview];
}];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GZ_RadioDetailsVC *rd = [[GZ_RadioDetailsVC alloc] init];
    rd.radioModel = _allArray[indexPath.row];
    rd.radioString = [_allArray[indexPath.row] radioid];
    rd.tempString = [[_allArray[indexPath.row] valueForKey:@"userinfo"] valueForKey:@"uname"];
    [self.navigationController pushViewController:rd animated:YES];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120 * FitHeight;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"GZ";
    GZRadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[GZRadioTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_allArray.count != 0) {
        cell.radioModel = _allArray[indexPath.row];
    }
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.2);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.2);
    }];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//头视图三张图点击方法
- (void)headerThreeImageTapAction:(UITapGestureRecognizer *)imageView
{
    UIImageView *image = (UIImageView *)imageView.view;
    GZ_HeaderImageVC *head = [[GZ_HeaderImageVC alloc] init];
    head.radioModel = _hArray[image.tag - 1000];
    head.tempString = [[_hArray[image.tag - 1000] valueForKey:@"userinfo"] valueForKey:@"uname"];
    [self.navigationController pushViewController:head animated:YES];
}



//滚动图
//滚动视图相关方法
- (void)changeImage
{
    [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x + ScreenWidth, 0) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(_scrollView.contentOffset.x  >= ScreenWidth * (_scrollArray.count + 1)) {
        [_scrollView setContentOffset:CGPointMake(ScreenWidth, 0) animated:NO];
        _pageControl.currentPage = 0;
    }else if(_scrollView.contentOffset.x  == 0) {
        [_scrollView setContentOffset:CGPointMake(ScreenWidth * _scrollArray.count, 0) animated:NO];
        _pageControl.currentPage = _scrollArray.count;
    }else{
        _pageControl.currentPage = (_scrollView.contentOffset.x - ScreenWidth) / ScreenWidth;
    }
    [_timer invalidate];

   
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
     _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}




- (void)pageControlAction
{
    [_scrollView setContentOffset:CGPointMake(ScreenWidth * (_pageControl.currentPage + 1), 0) animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
